<template>
	<div class="index_contribute_stat">
		<div class="item" v-for="(item, index) in countStatData" :key="index">
			<h2>{{ item.name }}投稿统计</h2>
			<dl v-for="(v, i) in item.children" :key="i" v-if="i < 2">
				<dt>{{ v.name }}</dt>
				<dd><countTo :start-val="v.startValue" :end-val="v.endValue" separator="" /></dd>
			</dl>
		</div>
	</div>
</template>

<script>
import countTo from 'vue-count-to';
import { getDepartListData } from '@/api/system/depart';
import { getNewsCountByDepart } from '@/api/web/sysNewsContents';
export default {
	components: { countTo },
	data() {
		return {
			departData: [],
			countStatData: []
		};
	},
	mounted() {
		this.initializePage();
	},
	methods: {
		//初始化页面
		async initializePage() {
			await this.getDepartData();
			await this.getNewsCount();
		},
		//获取部门列表
		async getDepartData() {
			let result = await getDepartListData({ pId: '0', extFiled1: '1' }).then((res) => res.data);
			if (result.code === '0') {
				let datas = !result.data ? [] : [...result.data];
				this.departData = datas.filter((item, index) => index < 2);
			}
		},

		//获取部门发布文章数量
		async getNewsCount() {
			let flatData = this.$treeToFlat(this.departData).filter((item) => item.level === '2' && item.extFiled1 === '1');
			let deptIds = flatData.map((item) => item.id);
			let result = await getNewsCountByDepart({ deptIds, flag: '1' }).then((res) => res.data);
			if (result.code === '0') {
				this.formatNewsCount(!result.data ? {} : { ...result.data[0] });
			}
		},

		//格式化数据
		async formatNewsCount(data) {
			let flatData = this.$treeToFlat(this.countStatData.length > 0 ? this.countStatData : this.departData);
			let flatDataArr = flatData.filter((item) => item.level === '1' || item.extFiled1 === '1');
			let countData = flatDataArr.map((item) => {
				let obj = { ...item };
				if (Object.keys(data).some((v) => v === item.id)) {
					this.$set(obj, 'startValue', parseInt(item.endValue || 0));
					this.$set(obj, 'endValue', parseInt(data[item.id]));
				}
				return obj;
			});
			this.countStatData = this.$flatToTree(countData, 'pid');
		}
	}
};
</script>

<style lang="scss" scoped>
.index_contribute_stat {
	display: flex;
	justify-content: space-between;
	.item {
		display: flex;
		align-items: center;
		width: 49.5%;
		height: 100px;
		background-color: rgba(0, 0, 0, 0.05);
		h2 {
			display: flex;
			align-items: center;
			font-size: 20px;
			padding: 0 40px;
			color: #357c65;
			flex-shrink: 0;
			&::after {
				content: '|';
				font-weight: normal;
				margin-left: 25px;
			}
		}
		dl {
			flex: 1;
			dt {
				font-size: 18px;
				color: #666;
				margin-bottom: 10px;
			}
			dd {
				font-size: 32px;
				line-height: 1;
				font-weight: bold;
				color: #e88227;
			}
		}
	}
}
</style>
